package com.cctc.juc.common.thread.threadpool.holder;

import com.cctc.juc.common.thread.ShutdownHookThread;
import com.cctc.juc.common.thread.threadpool.config.ThreadPoolConfig;
import com.cctc.juc.common.util.ThreadUtils;

import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * I/O 密集型任务线程池。
 * - 懒汉式创建单例 I/O 密集型任务线程池，用于执行 I/O 密集型任务。
 */
public class IoIntenseTargetThreadPoolLazyHolder {
    private static final ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(
            ThreadPoolConfig.IO_MAXIMUM_POOL_SIZE, ThreadPoolConfig.IO_MAXIMUM_POOL_SIZE,
            ThreadPoolConfig.KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(ThreadPoolConfig.WORK_QUEUE_SIZE),
            new ThreadUtils.AppThreadFactory("io"),
            new ThreadPoolExecutor.DiscardPolicy()
    );

    public static ThreadPoolExecutor getExecutor() {
        return EXECUTOR;
    }

    static {
        // 允许回收空闲超时的核心线程
        EXECUTOR.allowCoreThreadTimeOut(true);
        // JVM 进程关闭时的钩子函数
        Runtime.getRuntime().addShutdownHook(new ShutdownHookThread("I/O 密集型任务线程池", () -> {
            // 优雅终止线程池
            ThreadUtils.shutdownThreadPoolGracefully(EXECUTOR);
            return null;
        }));
    }

}
